import json
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import JsonResponse
from django.shortcuts import render
from Django_Admin.enumType import FrequencyDesc, RunStatus
from trade.models import TBackRun
from Strategy.models import TStrategy
# Create your views here.

# 回测管理
from django.views import View

# 回测列表
from Django_Admin.settings import backtest_col, sim_backtest_col, all_strategy


# 指定页面
class backtest(View):

    # 点击策略管理页面的查看回测按钮和点击左侧栏回测管理按钮时调用
    def get(self, request):
        request.session['d'] = 'b'
        request.session['sim_sid'] = None
        if request.GET.get('strategyId', None) is None:
            request.session['s'] = None
        elif request.GET.get("strategyId"):
            stgid = request.GET.get("strategyId")
        res = render(request, "backtest.html", {'t': 'b', 'stgid': stgid})
        return res

    # ajax请求回测列表时调用
    def post(self, request):
        dataTable = {}
        aodata = json.loads(request.POST.get("aodata"))
        for item in aodata:
            if item['name'] == "sEcho":
                sEcho = int(item['value'])  # 客户端发送的标识
            if item['name'] == "iDisplayStart":
                iDisplayStart = int(item['value'])  # 起始索引
            if item['name'] == "iDisplayLength":
                iDisplayLength = int(item['value'])  # 每页显示的行数

        strategyId = request.POST.get("strategyId")
        stgname = request.POST.get("stgname", None)
        sim_sid = request.session.get('sim_sid', None)
        if stgname is None:
            backlist = TBackRun.objects.values().filter(StgID=strategyId).order_by("-StartTime")
        else:
            # if (not sim_sid) and request.session.get('d', None) == 'b':
            #     if request.session.get('s', None) is None:
            StgIDs = TStrategy.objects.values("StgID").filter(StgID=strategyId,
                                                              StgName__contains=stgname).distinct()
            # StgIDs = all_strategy.find({'StgName': {"$regex": strategyId}}).distinct('StgID')
            backlist = TBackRun.objects.values().filter(StgID__in=StgIDs).order_by("-BatchID")
            # userList = backtest_col.find({'StgID': {"$in": StgIDs}}).sort('BatchID', -1)
            # else:
            #     request.session['s'] = None
            #     backlist = TBackRun.objects.values().filter(StgID=strategyId).order_by("-BatchID")
            # userList = backtest_col.find({'StgID': strategyId}).sort('BatchID', -1)
        resultLength = backlist.count()
        # 对list进行分页
        paginator = Paginator(list(backlist), iDisplayLength)
        # 把商品分成 10 个一页。
        try:
            warning_list = paginator.page(iDisplayStart / 10 + 1)
        # 请求页数错误
        except PageNotAnInteger:
            warning_list = paginator.page(1)
        except EmptyPage:
            warning_list = paginator.page(paginator.num_pages)
        data = []
        for item in warning_list:
            StgName = TStrategy.objects.values("StgName").filter(StgID=item['StgID'])
            StgName = list(StgName)
            # StgName = all_strategy.find({'StgID': item['StgID']}, {'StgName': 1, '_id': 0}).distinct('StgName')
            StgName = StgName[0].get("StgName") if StgName else ''

            row = {
                'StrategyId': item['StgID'],
                "StrategyName": StgName,
                "BacktestID": item['BatchID'],
                "BackTestTime": str(item['StartTime']).split('.')[0],
                "StartTime": item['Region'].split(',')[0],
                "EndTime": item['Region'].split(',')[1],
                "Frequency": FrequencyDesc.get(str(item['Frequency']), ''),
                "RunStatus": RunStatus[item['RunStatus']]
            }
            data.append(row)
        if strategyId != '':
            data = sorted(data, key=lambda item: int(item["BacktestID"]), reverse=True)
        dataTable['iTotalRecords'] = resultLength  # 数据总条数
        dataTable['sEcho'] = sEcho + 1
        dataTable['iTotalDisplayRecords'] = resultLength  # 显示的条数
        dataTable['aaData'] = data

        return JsonResponse(dataTable, safe=False)


def sim(request):
    request.session['d'] = 's'
    if request.GET.get('strategyId', None):
        request.session['sim_sid'] = request.GET['strategyId']
    else:
        request.session['s'] = None
    res = render(request, 'backtest.html')
    return res
